﻿using System;
using System.Security.Policy;
using MeterReader.Models;
using MeterReader.PubSubEvents;
using MeterReader.Services;
using MeterReader.Views;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;

namespace MeterReader.ViewModels
{
    public class MainWindowViewModel : BindableBase
    {
        private readonly IRegionManager _regionManager;
        private readonly IEventAggregator _eventAggregator;
        private readonly IDataService _dataService;

        public MainWindowViewModel(IRegionManager regionManager, IEventAggregator eventAggregator, IDataService dataService)
        {
            _regionManager = regionManager;
            _eventAggregator = eventAggregator;
            _dataService = dataService;
            _regionManager.RegisterViewWithRegion("MainRegion", "MetersDataMonitor");
            _eventAggregator.GetEvent<WorkStatusChangedEvent>().Subscribe(UpdateWorkStatus, (workStatus) => workStatus.Token == "WorkStatus");
            _eventAggregator.GetEvent<WorkStatusChangedEvent>().Subscribe(PopupOpen, (workStatus) => workStatus.Token == "Exception");
            _eventAggregator.GetEvent<NavigateEvent>().Subscribe(NavigateTo);
            StopAppCommand = new DelegateCommand(StopApp);
        }

        #region EventAction
        private void PopupOpen(WorkStatus status)
        {
            FaultMessage = status.Message;
            IsPopupOpen = true;
        }

        private void UpdateWorkStatus(WorkStatus status) => IsWorking = status.IsWorking;

        private void NavigateTo(string obj) => _regionManager.RequestNavigate("MainRegion", obj);

        #endregion EventAction


        #region Properties
        private string _faultMessage;
        public string FaultMessage
        {
            get { return _faultMessage; }
            set { SetProperty(ref _faultMessage, value); }
        }
        private bool _isPopupOpen;
        public bool IsPopupOpen
        {
            get { return _isPopupOpen; }
            set { SetProperty(ref _isPopupOpen, value); }
        }

        private bool _isWorking;
        public bool IsWorking
        {
            get { return _isWorking; }
            set { SetProperty(ref _isWorking, value); }
        }

        public DelegateCommand StopAppCommand { get; set; }
        #endregion

        /// <summary>
        /// 退出App执行，断开读取
        /// </summary>
        private void StopApp() => _dataService!.StopPeriodicRead();
    }
}
